package com.yun.many.auth.controller;

import cn.hutool.jwt.JWT;
import com.yun.many.auth.config.SecurityConfigProperties;
import com.yun.many.auth.model.dto.LoginUser;
import com.yun.many.auth.model.req.LoginReq;
import com.yun.many.auth.utils.LoginContext;
import com.yun.many.spec.enums.ResultCode;
import com.yun.many.spec.exception.ExceptionUtils;
import com.yun.many.spec.vo.HttpResult;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

@RestController
@RequiredArgsConstructor
public class PortalController extends BaseController {
    private final AuthenticationManager authenticationManager;
    private final SecurityConfigProperties securityConfigProperties;

    @PostMapping("login")
    public HttpResult<LoginUser> login(@Validated LoginReq req, BindingResult result) {
        validate(result);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authenticate);
        SecurityContextHolder.setContext(context);

        String token = JWT.create().setPayload("username", req.getUsername())
                .setKey(securityConfigProperties.getSecret().getBytes(StandardCharsets.UTF_8)).sign();

        LoginUser loginUser = LoginContext.getLoginUser();
        if (Objects.isNull(loginUser)) {
            ExceptionUtils.throwException(ResultCode.UNAUTHORIZED);
        }
        loginUser.setToken(token);
        return HttpResult.success(loginUser);
    }
}
